package com.example.android


import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask

class MyEventChannel(messenger: BinaryMessenger) {

    private val channelName = "flutter.billionbottle.com/event-channel"
    private val channel: EventChannel
    private var events: EventChannel.EventSink? = null
    private var eventChannelCount = 20

    init {
        channel = EventChannel(messenger, channelName)
        channel.setStreamHandler(MyStreamHandler())
        starTimer()
    }

    private fun starTimer() {
        var timer = Timer().schedule(timerTask {
            GlobalScope.launch(Dispatchers.Main) {
                var map = mapOf("eventChannelCount" to eventChannelCount++,"eventChannel" to "eventChannel")
                events?.success(map)
            }
        }, 0, 1000)
    }


    inner class MyStreamHandler:EventChannel.StreamHandler{
        override fun onListen(arguments: Any?, pEvents: EventChannel.EventSink?) {
            events = pEvents
        }

        override fun onCancel(arguments: Any?) {
            events = null
        }
    }
}